import { stringify, parse } from 'qs'
import { getBaseUrl } from '@/api/request.js'
import http from '@/api/index.js'
import store from '../store'
const FormData = require('./wxFormdata/formData.js')
let startTime = '';


function uploadFile(file, extra = {} ) {
	return new Promise(resolve => {
		let formData = new FormData();
		// formData.append("nickname", this.userInfo.nickname);
		formData.appendFile(file.name, file.url);
		
		Object.keys(extra).forEach(key=>{
			formData.append(key, extra[key]);
		})
		let data = formData.getData();
		wx.request({
		  url: this.$getBaseUrl() + '/upload',
		  header: {
			'content-type': data.contentType,
			'Accept': 'application/json,text/plain, */*',
			'Authorization': getStorage('token') ?'Bearer '+ getStorage('token') : ''
		  },
		  method: 'post',
		  data: data.buffer,
		  success: (res) => {
			  resolve(res.data.data);
			  // console.log(res);
		
		  }
		});
	})
}
function throttle(func, delay) {
	startTime = Date.now() - delay;
	return (function() {
		let curTime = Date.now()
		let remaining = delay - (curTime - startTime)
		let context = this
		let args = arguments
		if (remaining <= 0) {
			func.apply(context, args)
			startTime = Date.now()
		} else {
			uni.showToast({
				title: '请勿频繁点击',
				icon: 'none'
			})
		}
	})()
}
let timer = null;
function debance(func){
	if (timer) {
		clearTimeout(timer)
	}
	timer = setTimeout(function () {
	       func();
			timer = undefined;
	}, 500)
}

function once(func) {
    let hasRun = false; // 标志变量，初始为false

    return function(...args) {
        if (!hasRun) {
            hasRun = true; // 执行一次后，将标志设置为true
            return func.apply(this, args);
        }
    };
}

function getQuery() {
	const pages = getCurrentPages()
	const curPage = pages[pages.length - 1]
	let options = curPage.options || curPage.$route.query
	if (options.scene) {
		let scene = parse(decodeURIComponent(options.scene))
		options = Object.assign({}, options, scene)
	}
	return options
}
function toast(message) {
	uni.showToast({
		title: message,
		icon: 'none',
		duration: 3000,
	})
}
function goPage (type, url) {
	switch(type) {
	    case 1: //保留当前页面，跳转到应用内的某个页面
	       uni.navigateTo({
	       	 url,
	       });
	       break;
	    case 2: //关闭当前页面，跳转到应用内的某个页面
	       uni.redirectTo({
	       	 url,
	       });
	       break;
		case 3: //关闭所有页面，打开到应用内的某个页面
		   uni.reLaunch({
		   	 url,
		   });
		   break;
	} 
}
function formatRichText(html){
  let newContent= html.replace(/\<img/gi, '<img style="max-width:100%;height:auto;display:block;"');
  return newContent;
}

function getStorage(key) {
	const storage = uni.getStorageSync(key)
	
	if (!storage) return null
	
	const { data, expiration } = storage
	const timestamp = Date.now()
	
	if (expiration && timestamp > expiration) {
		removeStorage(key)
		return null
	} else {
		return data
	}
}

function setStorage(key, value, time) {
	let storage = {
		data: value
	}
	if (time) {
		const timestamp = Date.now()
		const expiration = timestamp + time
		storage.expiration = expiration
	}
	
	uni.setStorageSync(key, storage)
}

function removeStorage(key) {
	uni.removeStorageSync(key)
}   

function getUniLogin(detail, source = 0, utm = 0) {
	return new Promise(resolve => {
		uni.login({
			success: function(res) {
				http.doAuthorise({
					code: res.code,
				}).then(data => {
						setStorage('token', data.access_token);
						// store.commit('initToken', res.data)
						resolve(data.access_token)
				})
			}
		})
	})
}

function getUserInfo() {
	return new Promise(resolve => {
		http.getUserInfo().then(res => {
			if (res.data && res.data.data) {
				setStorage('myShare_userInfo', res.data.data)
				store.commit('initToken', res.data.data)
				resolve()
			}
		})
	})
}

function base64src(base64data) {
	const fsm = wx.getFileSystemManager();
	const FILE_BASE_NAME = 'tmp_base64src';
  return new Promise((resolve, reject) => {
    const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
    if (!format) {
      reject(new Error('ERROR_BASE64SRC_PARSE'));
    }
    const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
    const buffer = wx.base64ToArrayBuffer(bodyData);
    fsm.writeFile({
      filePath,
      data: buffer,
      encoding: 'binary',
      success() {
        resolve(filePath);
      },
      fail() {
        reject(new Error('ERROR_BASE64SRC_WRITE'));
      },
    });
  });
};
// 时间戳转换为日期
function timestampToTime1(timestamp, detail) {
	if(!timestamp) {
		return ''
	}
    var date = new Date(timestamp); // 13位的时间戳
	
	// timestamp = String(timestamp).replace(/-/g, "/");
	// var date = new Date(Number(timestamp)); // 13位的时间戳
    var Y = date.getFullYear() + '年';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '月';
    var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + '日';
    var h = date.getHours() + ':';
    var m = date.getMinutes() + ':';
    var s = date.getSeconds();
	if (detail === 1) {
		return Y + M + D + '' + h + m + s;
	}
	else if (detail === 2) {
		return  M + D;
	}
	return Y + M + D;
}
// 时间戳转换为日期
function timestampToTime(timestamp, detail) {
	var date = new Date(timestamp); // 13位的时间戳
	// timestamp = String(timestamp).replace(/-/g, "/");
    // var date = new Date(Number(timestamp)); // 13位的时间戳
    var Y = date.getFullYear();
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    var s =  date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
	if (detail === 1) {
		return `${Y}-${M}-${D}  ${h}:${m}:${s}`;
	} else if (detail === 2) {
		return `${M}-${D}`;
	} else if (detail === 3) {
		return `${h}:${m}`;
	}else if (detail === 4) {
		return `${Y}-${M}-${D}  ${h}:${m}`;
	}
	return  `${Y}-${M}-${D}`;
}
function dateToTime(date) { 
	// date = String(date).replace(/-/g, "/");
	console.log(date, 'date');
	return new Date(date).getTime();
}
function isLogin() {
	return getStorage('userInfo')&& getStorage('userInfo').avatar && getStorage('userInfo').nickname;
}
function getPlatform() {
	switch (uni.getSystemInfoSync().platform) {
		case 'android':
			console.log('运行Android上');
			break;
		case 'ios':
			console.log('运行iOS上');
			break;
		default:
			console.log('运行在开发者工具上');
			break;
	}
	
}
 function formatNumber(num) {
	   num = Number(num).toFixed(2);
	   return Number(num) % 1 === 0 ? Math.floor(num) : num;
}
function getTopHeight() {
	 const result = uni.getSystemInfoSync();
	 return  result.safeArea.top
 }

export default {
	throttle,
	getQuery,
	toast,
	goPage,
	formatRichText,
	getStorage,
	setStorage,
	removeStorage,
	getUniLogin,
	getUserInfo,
	base64src,
	timestampToTime,
	isLogin,
	debance,
	uploadFile,
	formatNumber,
	timestampToTime1,
	getBaseUrl,
	dateToTime,
	once,
	// webViewBaseUrl: 'https://dev-api.midzus.com/map',
	webViewBaseUrl: 'https://backend.midzus.com/map',
	getTopHeight
}
